package com.yikome.blacklist.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yikome.common.CommonService;
import com.google.common.base.Preconditions;
import com.yikome.blacklist.entity.BlackList;
import com.yikome.blacklist.repository.BlackListRepository;
import com.yikome.blacklist.request.BlackListCreateRequest;
import com.yikome.blacklist.request.BlackListSearchRequest;

import cn.hutool.core.util.StrUtil;

@Service
public class BlackListService extends CommonService<BlackList, Long> {

	@Autowired
	private NamedParameterJdbcTemplate jdbcTemplate ;
	
	@Autowired
	private BlackListRepository blackListRepository ;

	public BlackList persistBlackList(BlackListCreateRequest blackListCreateRequest) {
		
		BlackList blackList = null ;
		
		if(blackListCreateRequest.getId() != null) {
			blackList = blackListRepository.findBlackList(blackListCreateRequest.getId());
			Preconditions.checkArgument(blackList != null, "要修改的数据不存在...");
			blackList.setTel(blackListCreateRequest.getTel().trim());
			blackList.setComments(blackListCreateRequest.getComments());
		}else {
			blackList = new BlackList();
			blackList.setTel(blackListCreateRequest.getTel().trim());
			blackList.setComments(blackListCreateRequest.getComments());
		}
		
		return blackListRepository.save(blackList);
		
	}

	@Transactional
	public void deleteBlackList(Long blackListId) {
		
		blackListRepository.deleteById(blackListId);
	}

	public Page<BlackList> findBlackList(BlackListSearchRequest blackListSearchRequest, Pageable pageable) {
		
		String contentSQL = "SELECT * FROM o_black_list WHERE o_black_list.yn = 1 " ;
		
		StringBuilder paramSQL = new StringBuilder();
		Map<String , Object> paramMap = new HashMap<>();
		
		if(StrUtil.isNotBlank(blackListSearchRequest.getTel())) {
			paramSQL.append("AND o_black_list.tel = :tel ");
			paramMap.put("tel", blackListSearchRequest.getTel().trim());
		}
		if(StrUtil.isNotBlank(blackListSearchRequest.getComments())) {
			paramSQL.append("AND o_black_list.comments LIKE :comments ");
			paramMap.put("comments", "%"+ blackListSearchRequest.getComments().trim() +"%");
		}
		
		String countSQL = "SELECT COUNT(1) FROM (" + contentSQL + paramSQL + ") T" ; 
		
		List<BlackList> content = jdbcTemplate.query(contentSQL + paramSQL, paramMap, new BeanPropertyRowMapper<>(BlackList.class));
		
		Long total = jdbcTemplate.queryForObject(countSQL, paramMap, Long.class);
		
		return new PageImpl<BlackList>(content, pageable, total);
	} 
}
